package com.tanhua.admin.service;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;

import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    public Map login(Map map) {
        //取出map中的值
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //从redis中取出验证码和用户输入的进行比较
        String s = redisTemplate.opsForValue().get(uuid);
        if (StringUtils.isEmpty(s) || !s.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(uuid);
        //从数据库中取出对应账号的密码进行比较
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        password = SecureUtil.md5(password);
        if (admin == null ||  !admin.getPassword().equals(password)) {
            throw new BusinessException("账号或用户名错误");
        }
        //相同通过用户id和用户名生成token
        Map map1 = new HashMap();
        map1.put("userId", admin.getId());
        map1.put("username", admin.getUsername());
        String token = JwtUtils.getToken(map1);
        //返回token
        Map map2 = new HashMap();
        map2.put("token", token);
        return map2;
    }

    public Admin getprofile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return admin;
    }
}
